package com.rayo.keyboxdemo;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.rayo.keyholder.data.KeyHolderData;
import com.rayo.keyholder.serialport.KeyHolderService;
import com.rayo.wallreader.utils.HexUtil;

/**
 * Describe：
 * Created by zxy
 * On 2021/3/31
 */
public class ControllerPresenter {

    public Context mContext;
    public IControllerView mControllerView;
    public static KeyHolderService mKeyHolderService;


    public ControllerPresenter(Context context,IControllerView controllerView){
        this.mContext =context;
        this.mControllerView = controllerView;
    }

    private BroadcastReceiver mKeyHolderReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder stringBuilder = new StringBuilder(64);
            final String action = intent.getAction();
            if (intent.getSerializableExtra(KeyHolderService.EXTRA_DATA) instanceof Integer) {
                return;
            }
            final KeyHolderData keyHolderData = (KeyHolderData) intent.getSerializableExtra(KeyHolderService.EXTRA_DATA);

                switch (action) {

                    case KeyHolderService.ACTION_DATA_WRITE:
                        stringBuilder.append("MainSend:");
                        stringBuilder.append(HexUtil.encodeHexStr(keyHolderData.getData()));
                        Log.e("write", stringBuilder.toString());
                        break;
                    case KeyHolderService.ACTION_DATA_READ:
                        Log.e("cmd", keyHolderData.getCmd() + "");
                        stringBuilder.append("MainRead:");
                        stringBuilder.append(String.format("%02X", keyHolderData.getCmd()) + "-");
                        stringBuilder.append(String.format("%02X", keyHolderData.getDeviceType()) + "-");
                        stringBuilder.append(String.format("%02X", keyHolderData.getAddress()) + "-");
                        stringBuilder.append(HexUtil.encodeHexStr(keyHolderData.getData()));

                        Log.e("read", stringBuilder.toString());

                        if (keyHolderData.getCmd()==-1){

                            if (HexUtil.encodeHexStr(keyHolderData.getData()).equals("01")){
                                mControllerView.cleanMsg();
                                mControllerView.setMsg("The address was set successfully");
                                mControllerView.showResultImage(true);
                            }
                        }else
                        if (keyHolderData.getCmd()==2){
                            if (HexUtil.encodeHexStr(keyHolderData.getData()).equals("01")) {
                                mControllerView.cleanMsg();
                                mControllerView.setMsg("open success");
                            }
                        }else if (keyHolderData.getCmd()==1){
                            if ((HexUtil.encodeHexStr(keyHolderData.getData()).startsWith("01", 0)) ){
                                mControllerView.cleanMsg();
                                StringBuffer stringBuffer = new StringBuffer();
                                stringBuffer.append("Type ："+String.format("%02X", keyHolderData.getDeviceType())+"\n");
                                stringBuffer.append( "Address ： "+ String.format("%02X", keyHolderData.getAddress()) +"\n");
                                stringBuffer.append("Tag ID : "+ HexUtil.encodeHexStr(keyHolderData.getData()).substring(14,22)+"\n");
                                stringBuffer.append("Lock : "+ getStatu(HexUtil.encodeHexStr(keyHolderData.getData()).substring(22,24))+"\n"
                                        +"Red light : " + getStatu(HexUtil.encodeHexStr(keyHolderData.getData()).substring(24,26))+"\n"
                                        +"Green light : " + getStatu(HexUtil.encodeHexStr(keyHolderData.getData()).substring(26,28))+"\n"
                                        +"Blue light : " + getStatu(HexUtil.encodeHexStr(keyHolderData.getData()).substring(28,30)));
                                mControllerView.setMsg(stringBuffer.toString());
                                mControllerView.showResultImage(true);
                            }
                        }
                        break;
                    case KeyHolderService.ACTION_CLOSE:
                        break;
                    default:
                        break;
                }
            }
    };



    public void start(Object o) {
        Intent service = new Intent(mContext, KeyHolderService.class);
        mContext.bindService(service, mKeyHolderConnection, Context.BIND_AUTO_CREATE);
        mContext.registerReceiver(mKeyHolderReceiver, makeUpdateIntentFilter());
    }

    private IntentFilter makeUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(KeyHolderService.ACTION_DATA_READ);
        intentFilter.addAction(KeyHolderService.ACTION_DATA_WRITE);
        intentFilter.addAction(KeyHolderService.ACTION_CLOSE);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        return intentFilter;
    }


    private ServiceConnection mKeyHolderConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mKeyHolderService = ((KeyHolderService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mKeyHolderService = null;

        }
    };
    public void destroy() {
        mContext.unregisterReceiver(mKeyHolderReceiver);
//        unregisterReceiver(mReceiver);
        try {
            if (mKeyHolderConnection != null)
                mContext. unbindService(mKeyHolderConnection);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("exx", e.toString());
        }
    }

    public void senData(KeyHolderData keyHolderData) {
        mKeyHolderService.sendData(keyHolderData);
    }

    public String getStatu(String statu){
        if (statu.equals("00"))
            return "Close";
        else
            return "Open";
    }
}
